//
//  TodoItem.swift
//  exam2
//
//  Created by stu on 2019/10/9.
//  Copyright © 2019年 stu. All rights reserved.
//

import Foundation
class TodoItem: NSObject,NSCoding {
    func encode(with aCoder: NSCoder) {
        aCoder.encode(text, forKey: "Text")
        aCoder.encode(checked, forKey: "Checked")
        aCoder.encode(dueDate, forKey: "DueDate")
         aCoder.encode(shouldRemind, forKey: "ShouldRemind")    }
    
    required init?(coder aDecoder: NSCoder) {
      text = aDecoder.decodeObject(forKey: "Text") as! String
        checked = aDecoder.decodeBool(forKey: "Checkrd")
        dueDate = aDecoder.decodeObject(forKey: "DueDate") as! Date
        shouldRemind = aDecoder.decodeBool(forKey: "ShouldRemind")
        
        
        super.init()
    }
    
    var text = ""
    var checked = false
    var dueDate = Date()
    var shouldRemind = false
    
    
    override init() {
        super.init()
    }
    func scheduleNotification() {
        removeNotification()
        if shouldRemind && dueDate > Date() {
            let content = UNMutableNotificationContent()
            content.title = "备忘录:"
            content.body = text
            content.sound = UNMotificationSound.default
            let calender = Calendar(identifier: .gregorian)
            let component = calender.dateComponents([.month, .day, .hour, .minute], from: dueDate)
            let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
            let request = UNNotificationRequest(identifier: text, content: content, trigger: trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request)
        }
    }
    func removeNotification() {
        let center = UNUserNotificationCenter.current()
        center.removePendingNotificationRequests(withIdentifiers: [text])
    }
    deinit {
        removeNotification()
    }
}
